/**
 * Created by MinTher on 2017/7/2.
 * @author:bjzhang
 */

'use strict';
import { CryptoJS } from './tripledes/tripledes';
import { api } from './api';
import Toast from "react-native-root-toast";
import {Alert} from "react-native";
const _ = {
    /**
     * @param {string} type
     * @param {string} url
     * @param {object} params
     */
    ajax(url,options){
        return new Promise(function(resolve,reject){
            fetch(api.base + url,options).then((response) => response.json()).then((responseData) => {
                console.log(responseData);
                if (responseData['header']) {
                    var code = responseData['header']['statusCode'];
                    if (code == 1000) {
                        resolve(responseData['data']);
                        return;
                    }else if(code == 1005 || code == 1006){
                        userInfo = null;
                        storage.save({key:'userinfo',data:userInfo });
                    }
                }
                reject(responseData['header']);
            }).catch((error) => {
                console.log(error);
                reject(error);
                return;
            });
        });
    },
    /**
     * @param {string} url
     * @param {object} params
     */
    post(url,params = {}){
        let id = 0 , token = 'e10adc3949ba59abbe56e057f20f883e';
        if(typeof userInfo != 'undefined' && userInfo && Object.keys(userInfo).length != 0){
            id = userInfo.id;
            token = userInfo.token;
        }
        let options = {
            method:'POST',
            headers:{
                'Content-Type': 'application/json; charset=UTF-8',
                'ActiveIdentify': id,
                'Header': JSON.stringify(_.renderHeader(url,id,token))
            },
            body:JSON.stringify(params)
        };
        return _.ajax(url,options);
    },

    /**
     *
     * @param {string} url
     * @param {object} params
     */
    get(url,args = {}){
        let id = 0 , token = 'e10adc3949ba59abbe56e057f20f883e';
        if(typeof userInfo != 'undefined' && userInfo && Object.keys(userInfo).length != 0) {
            id = userInfo.id;
            token = userInfo.token;
        }
        let options = {
            method:'GET',
            headers:{
                'Content-Type': 'application/json; charset=UTF-8',
                'ActiveIdentify': id,
                'Header': JSON.stringify(_.renderHeader(url,id,token))
            }
        };
        return _.ajax(url + _.toQueryString(args),options);
    },

    /**
     * Upload a file to the specified location
     * @param {string} domain
     * @param {string} store
     * @param {string} filePath
     */
    uploadFile(domain, store, filePath) {
        let id = 0 , token = 'e10adc3949ba59abbe56e057f20f883e';
        if(userInfo && Object.keys(userInfo).length != 0) {
            id = userInfo.id;
            token = userInfo.token;
        }
        return new Promise(function(resolve,reject){
            let formData = new FormData();
            var names = filePath.split('/');
            let file = {uri: filePath, type: 'multipart/form-data', name: names[names.length - 1]};
            formData.append('store', store);
            formData.append('files', file);
            fetch(api.base + domain,{
                method:'POST',
                headers:{
                    'Content-Type': 'multipart/form-data;charset=utf-8',
                    'ActiveIdentify': id,
                    'Header':JSON.stringify(_.renderHeader(domain,id,token))
                },
                body:formData
            }).then((response) => response.json()).then((responseData) => {
                if (responseData['header']) {
                    var code = responseData['header']['statusCode'];
                    if (code == 1000) {
                        resolve(responseData['data']);
                        return;
                    }
                }
                reject(responseData['header']);
            }).catch((error) => {
                reject(error);
            });
        });
    },
    /**
     * Get file suffix
     * @param {string} fileName
     */
    getSuffix(fileName){
        var idx = fileName.lastIndexOf('.');
        if(idx > -1)
            return fileName.substring(idx + 1,fileName.length);
        return 'mp4';
    },
    toQueryString(agrs){
        var query = [];
        for(var k in agrs){
            query.push(k + '=' + agrs[k]);
        }
        return '?' + query.join('&');
    },
    /**
     * encrypt string
     * @param {string} str
     * @param {string} key
     */
    desEncrypt(str,key){
        key = CryptoJS.enc.Base64.parse(key);
        // Triple DES 加密
        var encrypted = CryptoJS.TripleDES.encrypt(str, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        // 转换为字符串

        return encrypted = encrypted.toString();
    },
    /**
     * decrypt string
     * @param {string} ciphertext
     * @param {string} key
     */
    desDecrypt(ciphertext,key){
        key = CryptoJS.enc.Base64.parse(key);
        // Triple DES 解密
        var decrypted = CryptoJS.TripleDES.decrypt(ciphertext, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        // 转换为 utf8 字符串
        return CryptoJS.enc.Utf8.stringify(decrypted);
    },
    /**
     * render header
     * @param {string} cmd
     * @param {int} id
     */
    renderHeader(cmd,id,token){
        var tem = { deviceId: "", deviceName: "", osName: "", osVersion: "", versionName: "", versionCode: "6", token: token, cmd: cmd, source: 1, sign:'', timestamp: parseInt(new Date().getTime() / 1000) };
        tem.sign = _.desEncrypt(tem.cmd + '|' + id + '|' + tem.timestamp, tem.token);
        return tem;
    },
    getLocation(callback){
        navigator.geolocation.getCurrentPosition(
            (position) => {
                // alert(JSON.stringify(position));
                callback({ longitude:position.coords.longitude,latitude:position.coords.latitude });
            }, (error) => {
                Toast.show('获取您当前的位置失败',{
                    duration: Toast.durations.LONG,
                    position: Toast.positions.BOTTOM,
                });
                let location = { longitude:106.572, latitude:29.6323 };
                callback(location);
            }, {enableHighAccuracy: true, timeout: 10000, maximumAge: 1000}
        );
    },
    loginLose(navigation,statusCode){
        var state = false;
        if(statusCode == 1005){
            navigation.navigate('Login');
            state = true;
        }else if(statusCode == 1006){
            Alert.alert('账号在其他设备登陆',[{text:'确定',onPress:() => {
                    navigation.navigate('Login');
            }}]);
            state = true;
        }
        return state;
    }
};
module.exports = { common: {
    api:api,
    uploadFile : _.uploadFile ,
    post:_.post,
    get:_.get,
    getLocation:_.getLocation,
    loginLose:_.loginLose
} };